package cn.harry.cabinet.view.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.User
import cn.harry.cabinet.model.enums.Gender
import cn.harry.cabinet.model.enums.UserStatus
import cn.harry.cabinet.utils.DateConverter

/**
 * 用户列表适配器
 * 用于在RecyclerView中显示用户列表，支持分页加载
 */
class UserAdapter(
    private val onEditClick: (User) -> Unit,
    private val onDeleteClick: (User) -> Unit,
    private val onLoadMoreClick: (() -> Unit)? = null
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val VIEW_TYPE_USER = 0
        private const val VIEW_TYPE_LOAD_MORE = 1
    }

    private var users: List<User> = emptyList()
    private var showLoadMore = false
    private var isLoadingMore = false

    @SuppressLint("NotifyDataSetChanged")
    fun setUsers(newUsers: List<User>) {
        users = newUsers
        notifyDataSetChanged()
    }

    fun setShowLoadMore(show: Boolean) {
        if (showLoadMore != show) {
            showLoadMore = show
            if (show) {
                notifyItemInserted(itemCount - 1)
            } else {
                notifyItemRemoved(itemCount)
            }
        }
    }

    fun setLoadingMore(loading: Boolean) {
        isLoadingMore = loading
        if (showLoadMore) {
            notifyItemChanged(itemCount - 1)
        }
    }
    
    fun setNoMoreData(noMore: Boolean) {
        if (noMore && showLoadMore) {
            showLoadMore = false
            notifyItemRemoved(itemCount)
        }
    }
    
    fun isLoadingMore(): Boolean {
        return isLoadingMore
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == users.size && showLoadMore) VIEW_TYPE_LOAD_MORE else VIEW_TYPE_USER
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            VIEW_TYPE_USER -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_user, parent, false)
                UserViewHolder(view)
            }
            VIEW_TYPE_LOAD_MORE -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_load_more, parent, false)
                LoadMoreViewHolder(view)
            }
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is UserViewHolder -> holder.bind(users[position])
            is LoadMoreViewHolder -> holder.bind()
        }
    }

    override fun getItemCount(): Int = users.size + if (showLoadMore) 1 else 0

    inner class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bind(user: User) {
            // 设置用户基本信息
            itemView.findViewById<TextView>(R.id.userName).text = user.name
            itemView.findViewById<TextView>(R.id.userEmployeeId).text = "工号: ${user.employeeId}"
            itemView.findViewById<TextView>(R.id.userPhone).text = "手机: ${user.phoneNumber}"
            
            // 优化岗位显示，如果为空则显示"未设置"
            val positionView = itemView.findViewById<TextView>(R.id.userPosition)
            if (user.position.isNotBlank()) {
                positionView.text = "岗位: ${user.position}"
            } else {
                positionView.text = "岗位: 未设置"
            }
            
            itemView.findViewById<TextView>(R.id.userFeatureCode).text = "特征码: ${user.featureCode}"
            
            // 显示性别，转换为中文
            val genderView = itemView.findViewById<TextView>(R.id.userGender)
            val genderText = when (user.gender) {
                Gender.MALE -> "男"
                Gender.FEMALE -> "女"
            }
            genderView.text = "性别: $genderText"
            
            // 优化状态显示，使用不同颜色和中文
            val statusView = itemView.findViewById<TextView>(R.id.userStatus)
            val statusText = when (user.status) {
                UserStatus.ENABLED -> "启用"
                UserStatus.DISABLED -> "禁用"
            }
            statusView.text = "状态: $statusText"
            
            // 使用硬编码颜色值避免API兼容性问题
            when (user.status) {
                UserStatus.ENABLED -> statusView.setTextColor(0xFF4CAF50.toInt()) // 绿色
                UserStatus.DISABLED -> statusView.setTextColor(0xFFF44336.toInt()) // 红色
            }
            
            itemView.findViewById<TextView>(R.id.userCreateTime).text = "创建时间: ${DateConverter.Companion.dateToString(user.createTime)}"

            // 设置图标按钮点击事件
            val editButton = itemView.findViewById<ImageButton>(R.id.editButton)
            val deleteButton = itemView.findViewById<ImageButton>(R.id.deleteButton)
            
            // 设置点击事件
            editButton.setOnClickListener { onEditClick(user) }
            deleteButton.setOnClickListener { onDeleteClick(user) }
        }
    }

    inner class LoadMoreViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        
        fun bind() {
            val loadMoreText = itemView.findViewById<TextView>(R.id.loadMoreText)
            val loadMoreProgress = itemView.findViewById<View>(R.id.loadMoreProgress)
            
            if (isLoadingMore) {
                loadMoreText.text = "数据加载中..."
                loadMoreProgress.visibility = View.VISIBLE
                itemView.isClickable = false
                itemView.alpha = 0.7f
            } else {
                loadMoreText.text = "点击加载更多"
                loadMoreProgress.visibility = View.GONE
                itemView.isClickable = true
                itemView.alpha = 1.0f
            }
            
            itemView.setOnClickListener {
                if (!isLoadingMore) {
                    onLoadMoreClick?.invoke()
                }
            }
        }
    }
}